// pages/redEnvelopes/redEnvelopes.js
const app = getApp()
const utils = require('../../utils/util.js')
const CryptoJS = require('../../utils/aes-jia.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payment:0,
    type:null,
    pageNumber:1,
    receiveMoney:null,
    sendMoney:null,
    list:[],
    totalPages:null,
    openShow:false,
    returnShow:false,
    sendName:'',
    sendUrl:'',
    redBlessings:'',
    returnShow:false,
    gobackShow:false,
    receiveShow:false,
    redPacket:'',
    returninput:'',
    redId:'',
    actid:'',
    receiveUrl:'',
    receiveName:'',
    sendTime:'',
    walletBalance:'',
    whetherSetPayPwd:false,
    showPayPwdInput:false,
    amountRedEnvelope: '',
    amountRedEnvelopeico: '',
    userInfo:'',
    isOver:true,
    senderId:'',
    addToActivity:'',
  },
  payment(e) {
    var id = e.currentTarget.dataset.index
    this.setData({
      payment: id
    })
  },
  getredList(){
    var that = this
    var type = null
    var url = ''
    if (that.data.type == 1 || that.data.type == 4) {
      url = 'blessmini/rank/redList'
    } else if (that.data.type == 2 || that.data.type == 5){
      url = 'blessmini/rank/categoryList'
    } else if (that.data.type == 3 || that.data.type == 6){
      url = 'blessmini/rank/cashList'
    }
    if (that.data.type == 1 || that.data.type == 2 || that.data.type == 3){
      type = 1
    } else if (that.data.type == 4 || that.data.type == 5 || that.data.type == 6){
      type = 2
    }
    app.req({
      url: url,
      data: {
        pageNumber: that.data.pageNumber,
        pageSize: 10,
        type: type,
      },
      method: "post",
      success: function (res) {
        if (res.code == 200) {
          var rows =[]
          var totalPages=null
          if (that.data.type == 1 || that.data.type == 4){
            rows = res.data.list.rows
            totalPages = res.data.list.totalPages
          } else if (that.data.type == 2 || that.data.type == 5){
            rows = res.data.rows
            totalPages = res.data.totalPages
          } else if (that.data.type == 3 || that.data.type == 6){
            rows = res.data.page.rows
            totalPages = res.data.page.totalPages
          }
          if (rows){
            for (var item in rows) {
              rows[item].createTime = rows[item].createTime.substring(11, 16)
            }
          }
          if(that.data.pageNumber==1){
            that.setData({
              list: rows,
            })
          }else{
            that.setData({
              list: that.data.list.concat(rows)
            })
          }
          that.setData({
            receiveMoney: res.data.receiveMoney,
            sendMoney: res.data.sendMoney,
            totalPages: totalPages
          })
          console.log('红包', that.data.list)
        }
      }
    })
  },
  redopen(e){
    var that  = this
    var datetg = e.currentTarget.dataset
    app.req({
      url:'blessmini/redPacket/redPacketDetails',
      data:{
        id:datetg.id
      },
      method: "post",
      success:function(res){
        if(res.code==200){
          if (res.data.isOpen==0){
            that.setData({
              openShow: true,
            })
          }else{
            that.setData({
              receiveShow: true,
            })
          }
          if (res.data.openTime) {
            var time = utils.getTime(res.data.openTime)
          }
          that.setData({
            redId: datetg.id,
            actid: datetg.actid,
            sendName: res.data.senderName,
            sendUrl: res.data.senderUrl,
            redBlessings: res.data.content,
            redPacket: res.data.money,
            receiveUrl: res.data.receiverUrl,
            receiveName: res.data.receiverName,
            sendTime:time,
            senderId: res.data.sendId,
        })
          console.log('iddddd', e, datetg.actid)
      }
      }
    })
  },
  returnCeremony() {
    var that = this
    that.setData({
      gobackShow: true,
      receiveShow: false,
    })
  },
  returnBtn() {
    this.setData({
      openShow: false,
      returnShow: true,
    })
  },
  xClose() {
    this.setData({
      openShow: false,
    })
  },
  xClose1() {
    this.setData({
      receiveShow: false,
    })
  },
  xClosetwo() {
    this.setData({
      gobackShow: false,
    })
  },
  xClose2() {
    this.setData({
      returnShow: false,
    })
  },
  openRed() {
    var that = this
    var data = {}
    app.req({
      url: 'blessmini/redPacket/receiveRedPrivate',
      data: {
        redPrivateId:that.data.redId
        },
      method: "post",
      success: function (res) {
        if (res.code == 200) {
          wx.showToast({
            title: '领取成功',
          })
            that.setData({
              openShow: false,
              receiveShow: true,
            })
          that.onShow()
        }
      }
    })
  },
  //感谢
  returninput(e) {
    this.setData({
      returninput: e.detail.value
    })
  },
  returnRed() {
    var that = this
    if (that.data.returninput == '') {
      that.setData({
        returninput: '谢谢您的好意'
      })
    }
    app.req({
      url: "blessmini/redPacket/returnRedPrivate",
      method: "post",
      data: {
        id: that.data.redId,
        birthId: that.data.actid,
        content: that.data.returninput,
      },
      success: function (res) {
        if (200 == res.code) {
          wx.showToast({
            title: "红包已退回",
            duration: 2000
          })
          that.setData({
            returnShow: false
          })
          that.onShow()
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  givingAdviceInput: function (e) {
    this.setData({
      givingAdvice: e.detail.value.replace(/\s+/g, '')
    })
  },
  //支付
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.walletBalance < that.data.amountRedEnvelope) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd) {
          that.setData({
            showPayPwdInput: true,
            payFocus: true
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.navigateTo({
                  url: '/pages/password/password',
                })
              }
            }
          })
        }
      }
    }
  },
  addToActivity: function (e) {
    var timestamp = Date.parse(new Date()) / 1000;
    var that = this;
    var payWay = '';
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    var blessings = (that.data.givingAdvice == '' ? '万分感谢，小小心意，请笑纳' : that.data.givingAdvice)
    if (e == 0) {
      payWay = 0
    } else {
      payWay = e.currentTarget.dataset.id;
    }
    if (payWay == 1) {
      var sourceType = 5
    } else {
      var sourceType = ''
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      var userId = that.data.userInfo.id
      console.log("支付方式", payWay, that.data.actid)
      var data = {
        birthId: that.data.actid,
        sendId: userId,
        type: 2,
        receiveId: that.data.senderId,
        content: blessings,
        money: that.data.amountRedEnvelope,
        payWay: parseInt(payWay),
        id: that.data.redId,
        sourceType: sourceType,
        prepaymentRecordId: that.data.prepaymentRecordId,
      }
      console.log('传值', data)
      app.req({
        url: 'blessmini/redPacket/returnSalute',
        method: "post",
        showLoad: true,
        data: data,
        success: function (res) {
          console.log("支付", that.data.amountRedEnvelope, res)
          if (res.code == 200 && payWay == 0) {
            that.setData({
              showPopup: false,
              isOver: true
            })
            wx.showToast({
              title: "红包已回赠",
              duration: 2000
            })
            that.onShow()
          } else if (res.code == 200 && payWay == 1) {
            var paydata = res.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  showPopup: false,
                  isOver: true
                })
                wx.showToast({
                  title: "红包已回赠",
                  duration: 2000
                })
                that.onShow()
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.data.errMsg)
              }
            })
          } else {
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },
  returnfocus(e) {
    this.setData({
      amountRedEnvelopeico: ''
    })
  },
  //输入金额
  amountInput: function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    console.log('bug1')
    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      console.log('bug2')
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      console.log('bug3')
      e.detail.value = 500000
    }
    this.setData({
      amountRedEnvelope: e.detail.value,
    })

  },
  amountblur(e) {
    if (e.detail.value !== '') {
      this.setData({
        amountRedEnvelopeico: '￥' + this.data.amountRedEnvelope
      })
    }
  },
  returnCeremonySelection: function (e) {
    var that = this;
    if (that.data.amountRedEnvelope == 0 || that.data.amountRedEnvelope.length == 0) {
      wx.showToast({
        title: "请输入回礼金额",
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      that.setData({
        showPopup: true,
        gobackShow: false
      })
    }
  },
  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    app.req({
      url: "blessmini/user/myBalance",
      method: "post",
      data: '',
      success: function (res) {
        console.log('获取钱包余额', res)
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //预支付
  operationRecord() {
    var timestamp = Date.parse(new Date()) / 1000;
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "blessmini/webPayLog/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: ''
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: ''
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {
    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },

  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'blessmini/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      type: options.type
    })
    if(that.data.type==1){
      wx.setNavigationBarTitle({
        title: "收到的红包"
      })
    } else if (that.data.type == 2) {
      wx.setNavigationBarTitle({
        title: "收到的礼物"
      })
    } else if (that.data.type == 3) {
      wx.setNavigationBarTitle({
        title: "收到的礼金"
      })
    } else if (that.data.type == 4) {
      wx.setNavigationBarTitle({
        title: "发出的红包"
      })
    } else if (that.data.type == 5) {
      wx.setNavigationBarTitle({
        title: "发出的礼物"
      })
    } else if (that.data.type == 6) {
      wx.setNavigationBarTitle({
        title: "发出的礼金"
      })
    }
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({
      pageNumber:1
    })
    that.getredList()
    that.getWalletBalance()
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    console.log('加载更多1')
    if(that.data.totalPages > that.data.pageNumber){
      that.setData({
        pageNumber:that.data.pageNumber +1
      })
      console.log('加载更多2', that.data.pageNumber)
      that.getredList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})